import re
from rest_framework.views import APIView
from django.conf import settings
from . import models, serializers, throttles
from utilss.response import APIResponse
from django.core.cache import cache
from libs import tx_sms


# 多方式登录
class LoginAPIView(APIView):
    """
    多种登录方式接口
    """
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        多种登录接口
        :param request: 请求数据
        :param args:
        :param kwargs:

        """
        print
        # 反序列化校验数据
        serializer = serializers.LoginModelsSerializer(data=request.data)
        if serializer.is_valid():
            return APIResponse(0, "登录成功", results={
                "username": serializer.user.username,
                "token": serializer.token,
            })
        return APIResponse(1, "failed", results=serializer.errors, http_status=400)


# 手机验证码登录
class LoginMobileAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginMobileSerializer(data=request.data)

        if serializer.is_valid(raise_exception=True):
            return APIResponse(results={
                "username": serializer.user.username,
                "token": serializer.token
            })


# 手机验证码注册
class RegisterAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.RegisterModelSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user_obj = serializer.save()
            return APIResponse(results={
                "username": user_obj.username,
                "mobile": user_obj.mobile,
                "email": user_obj.email,
            })

        return APIResponse(1, '注册失败', data=serializer.errors, http_status=400)


# 发送短信
class SMSAPIView(APIView):
    throttle_classes = [throttles.SMSRateThrottle]

    def post(self, request, *args, **kwargs):
        mobile = request.data.get("mobile")
        if not re.match(r"^1[3-9][0-9]{9}$", mobile):
            return APIResponse(1, "手机号格式错误！")

        # 获取验证码
        code = tx_sms.get_code()

        # 发送短信
        result = tx_sms.send_sms(mobile, code, settings.SMS_EXP)

        # 服务器缓存验证码
        if not result:
            return APIResponse(1, "发送验证码失败！")

        # django数据库缓存
        cache.set(f"{settings.SMS_CACHE_KEY}{mobile}", code, settings.SMS_EXP)

        # 校验验证码与数据库缓存中验证码是否一样
        # print(code, cache.get(f"sms_{mobile}")) # 0662 0662

        return APIResponse(0, "验证码发送成功！")


# 手机注册验证
class MobileAPIView(APIView):
    """
    手机号注册验证
    """

    def post(self, request, *args, **kwargs):
        """
        判断手机号是否已经注册
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        mobile = request.data.get("mobile")
        if not re.match(r"^1[3-9][0-9]{9}$", mobile):
            return APIResponse(1, "手机号格式错误！")
        try:
            # 判断手机号是否已经注册(合理使用get与异常连用)
            models.User.objects.get(mobile=mobile)
            return APIResponse(1, "手机号已经注册！")
        except:
            # 没有注册过
            return APIResponse(0, "手机号未注册！")
